package com.hudongwx.godoffood.fragment.communityFragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.Community_Activity.CommunityActivity;
import com.hudongwx.godoffood.activity.Community_Activity.DetailsActivity;
import com.hudongwx.godoffood.fragment.communityFragment.viewPager.ImageActivity;
import com.hudongwx.godoffood.resfRecycle.MyItemDecoration;
import com.hudongwx.godoffood.resfRecycle.MyRecyclerView;
import com.hudongwx.godoffood.utils.API.API;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
@ContentView(R.layout.fragment_show_dan)
public class ShowDanFragment extends Fragment {
    private View view = null;
    private String TAG = "ShowDanFragment";
    @ViewInject(R.id.showdan_recycle)
    private MyRecyclerView recyclerView;
    Handler h = new Handler();
    private String postId;
    private int page = 1; //页数
    private MyShowAdapter adapter;
    private LinearLayoutManager linear;
    private Handler handler = new Handler();

    public ShowDanFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null == view) {
            view = x.view().inject(this, inflater, container);
            init();
            recyclerView.addItemDecoration(new MyItemDecoration());
            recyclerView.setMyRecyclerViewListener(new MyRecyclerView.MyRecyclerViewListener() {
                @Override
                public void onRefresh() {
                    h.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            recyclerView.setRefreshComplete();
                            adapter.clearData();
                            page = 1;
                            init();
                        }
                    }, 1500);
                }

                @Override
                public void onLoadMore() {
                    init();
                    h.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            recyclerView.setLoadMoreComplete();
                        }
                    }, 1000);
                }//
            });


        }
        return view;
    }


    //初始化加载数据
    private void init() {
        final RequestParams requesParams = new RequestParams(API.getShowdanUrl(page));
        x.http().get(requesParams, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    int length = result.getJSONArray("Data").length();
                    if (length == 0) {
                        Toast.makeText(getContext(), "没有更多数据", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                List<JSONObject> jsonObjects = parser2ListItem(result);
                //处理数据
                if (page == 1) {
                    initView(jsonObjects);
                } else {
                    adapter.addMore(jsonObjects);
                }
                page++;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    //初始化数据
    private void initView(List<JSONObject> jsonobect) {
        adapter = new MyShowAdapter(jsonobect);
        //获取线性布局管理器
        linear = new LinearLayoutManager(getContext());
        //设置管理器
        recyclerView.setLayoutManager(linear);
        //设置适配器
        recyclerView.setAdapter(adapter);
    }

    //适配器
    class MyShowAdapter extends RecyclerView.Adapter<MyViewHolder> {
        private List<JSONObject> data;

        public MyShowAdapter(List<JSONObject> list) {
            this.data = list;
        }

        /**
         * 加载新的一页的时候，加载数据
         *
         * @param
         */
        public void addMore(List<JSONObject> list) {
            data.addAll(list);
            notifyItemRangeChanged(this.data.size() - list.size(), list.size());
        }

        //刷新清除数据
        public void clearData() {
            data.clear();
            notifyDataSetChanged();
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //设置parent 后才能让recyclerview的宽度才会不出错
            View view = LayoutInflater.from(getContext()).inflate(R.layout.recommend_showdan_item, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            try {
                setOnItemClickListener listener = new setOnItemClickListener();
                JSONObject item = data.get(position);
                JSONArray imageitem = item.getJSONArray("ListFile");
                x.image().bind(holder.iv, item.getString("UserIcon"));
                holder.tv1.setText(item.getString("UserName"));
                holder.tv2.setText(item.getString("DateTime"));
                holder.tv3.setText(item.getString("Title"));
                String content = item.getString("Content");
                if (!"".equals(content)) {
                    holder.tv4.setVisibility(View.VISIBLE);
                    holder.tv4.setText(item.getString("Content"));
                }
                int counthuitie = item.getInt("CommentCount");
                if (counthuitie > 0) {
                    holder.tv5.setText(counthuitie + "");
                }
                holder.iv.setTag(item.getString("CloudId"));
                holder.iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent=new Intent(getContext(), CommunityActivity.class);
                        String clouid= (String) v.getTag();
                        intent.putExtra("couldId",clouid);
                        startActivity(intent);
                    }
                });
                ItemAdapter itemAdapter = new ItemAdapter(imageitem);
                holder.gridView.setAdapter(itemAdapter);
                postId = item.getString("Id") + "";
                holder.ll.setTag(postId);
                holder.ll.setOnClickListener(listener);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }

    /**
     * 这是主item的装载
     */
    class MyViewHolder extends RecyclerView.ViewHolder {

        private ImageView iv;
        private TextView tv1, tv2, tv3, tv4, tv5;
        private GridView gridView;
        private LinearLayout ll;

        public MyViewHolder(View itemView) {
            super(itemView);
            gridView = (GridView) itemView.findViewById(R.id.showan_gridview);
            iv = (ImageView) itemView.findViewById(R.id.Recommend_showdan_iv);
            tv1 = (TextView) itemView.findViewById(R.id.showdan_tv1);
            tv2 = (TextView) itemView.findViewById(R.id.showdan_tv2);
            tv3 = (TextView) itemView.findViewById(R.id.showdan_tv3);
            tv4 = (TextView) itemView.findViewById(R.id.showdan_tv4);
            tv5 = (TextView) itemView.findViewById(R.id.showdan_tv5);
            ll = (LinearLayout) itemView.findViewById(R.id.showdan_ll);
        }
    }

    /**
     * 把获取到的json数据，解析添加到一个List里面
     *
     * @param data
     * @return
     */
    private List<JSONObject> parser2ListItem(JSONObject data) {
        List<JSONObject> list = new ArrayList<>();
        try {
            JSONArray jsonArray = data.getJSONArray("Data");
            int len = jsonArray.length();
            for (int i = 0; i < len; i++) {
                list.add(jsonArray.getJSONObject(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 这是小图片的适配器
     */
    class ItemAdapter extends BaseAdapter {
        private JSONArray data;
        //创建一个集合装载图片
        private ArrayList<String> list = new ArrayList<>();

        public ItemAdapter(JSONArray data) {
            this.data = data;
            addlist();
        }

        //将图片的地址添加进集合
        public void addlist() {
            for (int i = 0; i < data.length(); i++) {
                try {
                    list.add(data.getJSONObject(i).getString("Url"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public int getCount() {
            return data.length();

        }

        @Override
        public Object getItem(int position) {
            try {
                return data.getJSONObject(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageItemHolder imageItemHolder = null;
            gridViewClickListener gridViewclickListener = new gridViewClickListener();
            if (convertView == null) {
                imageItemHolder = new ImageItemHolder();
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.gridview_showdan_image, null);
                imageItemHolder.iv1 = (ImageView) convertView.findViewById(R.id.showdan_image3);
                convertView.setTag(imageItemHolder);
            } else {
                imageItemHolder = (ImageItemHolder) convertView.getTag();
            }
            try {
                String imageurl = data.getJSONObject(position).getString("Url");
                x.image().bind(imageItemHolder.iv1, imageurl);
                Map<String,Object> map=new HashMap<>();
                map.put("list",list);
                map.put("position",position);
                imageItemHolder.iv1.setTag(map);
                imageItemHolder.iv1.setOnClickListener(gridViewclickListener);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }

    class ImageItemHolder {
        private ImageView iv1;
    }

    //条目点击事件
    class setOnItemClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "onClick: tiaoz");
            String postid = (String) v.getTag();
            Intent intent = new Intent(getContext(), DetailsActivity.class);
            intent.putExtra("postid", postid);
            startActivity(intent);
        }
    }

    //gridview 的点击事件
    class gridViewClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Map<String, Object> map = (Map<String, Object>) v.getTag();
            ArrayList<String> list = (ArrayList<String>) map.get("list");
            int position = (int) map.get("position");
            Intent intent = new Intent(getContext(), ImageActivity.class);
            intent.putExtra("position", position);
            intent.putStringArrayListExtra("list", list);
            startActivity(intent);
        }
    }
}
